package com.example.thumbsupdemo

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Paint.FontMetrics
import android.graphics.PointF
import android.util.Log
import android.view.View
import android.widget.TextView

private const val TAG = "CountView"

/**
 * 点赞数量部分
 *
 * 如何计算数字的长宽呢？
 */
class CountView(context: Context) : View(context) {

    private val mPaint = Paint()

    private var mCount = 100
    private var mCountString = ""
    private var mStringWidth = 0F
    private val mCheckedColor = context.getColor(R.color.checked)
    private val mUncheckedColor = context.getColor(R.color.unchecked)

    init {
        mPaint.isAntiAlias = true
        // 实心字体
        mPaint.style = Paint.Style.FILL
        mPaint.color = mUncheckedColor
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        // 测量出长宽后，计算字符串的长宽
        val textSize = getTextSize(measuredHeight)
        mPaint.textSize = textSize
        // 初始设置五位长度，这样就不会超出了
        mStringWidth = mPaint.measureText("00000")
        setMeasuredDimension(mStringWidth.toInt(), measuredHeight)
    }

    fun setDefaultCount(count: Int) {
        mCount = count
        resetString(mCount)

    }

    private fun resetString(count: Int) {
        if (count < 10000) {
            mCountString = count.toString()
        } else {
            val num = count / 10000
            mCountString = "${num}万"
        }
        invalidate()
    }

    /**
     * 快速点击时，得保证拇指和数字的状态匹配
     */
    fun onClick(checked: Boolean) {
        if (checked) {
            mPaint.color = mCheckedColor
            resetString(++mCount)
        } else {
            mPaint.color = mUncheckedColor
            resetString(--mCount)
        }
    }

    /**
     * 根据布局的高度计算出合适的字体大小
     * 字体大小为高度的一半
     * 这个数字和draw里的数字都是随便试出来的，跟着感觉走
     *
     * @param height 布局的高度
     * @return 字体大小，单位px
     */
    private fun getTextSize(height: Int): Float {
        return height * 0.75F
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // 坐标代表字符串的左下角再靠左一点的位置
        canvas.drawText(mCountString, 0F, height * 0.815F, mPaint)
    }
}